#!/usr/bin/env bash

# DESCRIPTION
#     This script corrects an error within Qt5 Chromium library used by the
#     official "classic" Genshin launcher across (almost?) all versions.
#     This script is needed since approx. Wine 9.8.
#
#     How to use: Execute this script within your launcher installation directory.
#     Example:    bash /path/to/repo/compat/Qt5WebEngineCore_patch.sh
#
# IMPLEMENTATION DETAILS
#     This patch adds an additional `if (sacl == nullptr) return ERROR_SUCCCESS;`
#     check in between the following lines: https://github.com/qt/qtwebengine-chromium/blob/69-based/chromium/sandbox/win/src/restricted_token_utils.cc#L289-L291
#
# EXIT STATUS
#     0      : The patch was applied successfully or is not needed by your system.
#     other  : Patch failure. See stdout or stderr output for details.


DIR=$(dirname "${BASH_SOURCE[0]}")
FILE="Qt5WebEngineCore.dll"

if [ ! -e "$FILE" ]; then
	echo "[ERROR] File '$FILE' not found. Please check the script usage notes."
fi

sum=($(md5sum $FILE))

if [[ "$sum" != "6c3e89dfd553a91055959f5f21584931" ]]; then
	# The patch might corrupt invalid/outdated files if this check is skippd.
	echo "[ERROR] Wrong file version or the patch is already applied"
	echo " -> md5sum: ${sum}" && exit 1
fi

if ! command -v xdelta3 &>/dev/null; then
	echo "[ERROR] xdelta3 application is required"
	echo " -> Debian/Ubuntu: apt install xdelta3"
	echo " -> Fedora: dnf install xdelta"
	echo " -> Arch/Arch-based: pacman -S xdelta3"
	echo " -> macOS: \"port install xdelta\" or \"brew install xdelta\""
	exit 1
fi

echo "--- Patching $FILE"

xdelta_fail() {
	mv -vf "$FILE.bak" "$FILE"
	exit 1
}

mv -f "$FILE" "$FILE.bak"
xdelta3 -d -s "$FILE.bak" "$DIR/Qt5WebEngineCore_patch.vcdiff" "$FILE" || xdelta_fail

echo "==> Patch applied successfully"
exit 0
